package com.ckr.common.exception;

import com.ckr.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理，@ControllerAdvice(@RestControllerAdvice) 配合 @ExceptionHandler 实现全局异常处理
 *
 * @author Shadowckr
 * @create 2022-02-07 21:58
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 401 ShiroException.class
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e) {
        //noinspection PlaceholderCountMatchesArgumentCount
        log.error("ShiroException：-----------------{}", e);
        return Result.fail(401, e.getMessage(), null);
    }

    // 400 RuntimeException.class
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e) {
        //noinspection PlaceholderCountMatchesArgumentCount
        log.error("RuntimeException：-----------------{}", e);
        return Result.fail(e.getMessage());
    }

    // 400 MethodArgumentNotValidException.class 实体校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) {
        //noinspection PlaceholderCountMatchesArgumentCount
        log.error("MethodArgumentNotValidException：-----------------{}", e);
        BindingResult bindingException = e.getBindingResult();
        // 如果有多个异常，则按顺序抛出
        //noinspection OptionalGetWithoutIsPresent
        ObjectError objectError = bindingException.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());
    }

    // 400 IllegalArgumentException.class (Assert)断言异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        //noinspection PlaceholderCountMatchesArgumentCount
        log.error("IllegalArgumentException：----------------{}", e);
        return Result.fail(e.getMessage());
    }
}
